﻿using System;
using System.Collections;
using System.Web;
using viPage.Controllers;
using visinia.SmartEngine;
using viPage.Classes;

namespace viPage.HttpModules
{
    /// <summary>
    /// The url rewriter
    /// </summary>
    public class UrlRewriter : BaseUrlRewriter
    {
        public override string RewriteUrl(HttpApplication httpApp, IEnumerator urlEnum)
        {
            HttpContext context = ((HttpApplication)httpApp).Context;
            return HandleURL(context, urlEnum);
        }

        /*****************************************************************************************/
        // Page URL = Page/PageId/some.thing.imp.aspx        
        /*****************************************************************************************/

        private string HandleURL(HttpContext context, IEnumerator urlEnum)
        {
            string root = WebRoots.GetRelativeWebRoot;
            if (!urlEnum.MoveNext())           
                return null;            
            // display the page            
            viPageInfo page = viPageController.GetPage(TrimExtension(HttpUtility.UrlDecode((string)urlEnum.Current)));
            if (page != null)
                return root + "Default.aspx?PageId=" + page.WebPageId;
            return null;
        }

        private string TrimExtension(string url)
        {
            if (url.EndsWith(".aspx"))
                return url.Remove(url.LastIndexOf('.'));
            else
                return url;
        }
    }
}
